﻿using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
//using System.Web.Mail;
using System.Net.Mail;
using System.Net;
//using Gmail;
using System.Net.Mime;
using System.Configuration;
using System.Text;
using System.IO;
using LPV_POS.Module;
using LPV_POS;
//using System.Web.Mail;

namespace LPV.SendMail
{
	/// <summary>
	/// Summary description for frmSendMail.
	/// </summary>
	public class frmSendMail : System.Windows.Forms.Form
    {
		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.Label label2;
		private System.Windows.Forms.Label label3;
		private System.Windows.Forms.TextBox txtto;
		private System.Windows.Forms.RichTextBox txtbody;
		private System.Windows.Forms.TextBox txtsubject;
		private System.Windows.Forms.TextBox txtfrom;
		private System.Windows.Forms.Label label4;
        private TextBox txtPass;
        private Label label5;
        private Timer timer1;
        private Button button5;
        private Label label6;
        private TextBox txtAttachFile;
        private Label label7;
        private TextBox txtSender;
        private Button button6;
        private IContainer components;

		public frmSendMail()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();
            InitControl();
			//
			// TODO: Add any constructor code after InitializeComponent call
			//
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
            this.components = new System.ComponentModel.Container();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmSendMail));
            this.txtto = new System.Windows.Forms.TextBox();
            this.label1 = new System.Windows.Forms.Label();
            this.txtbody = new System.Windows.Forms.RichTextBox();
            this.label2 = new System.Windows.Forms.Label();
            this.label3 = new System.Windows.Forms.Label();
            this.txtsubject = new System.Windows.Forms.TextBox();
            this.txtfrom = new System.Windows.Forms.TextBox();
            this.label4 = new System.Windows.Forms.Label();
            this.txtPass = new System.Windows.Forms.TextBox();
            this.label5 = new System.Windows.Forms.Label();
            this.timer1 = new System.Windows.Forms.Timer(this.components);
            this.button5 = new System.Windows.Forms.Button();
            this.label6 = new System.Windows.Forms.Label();
            this.txtAttachFile = new System.Windows.Forms.TextBox();
            this.label7 = new System.Windows.Forms.Label();
            this.txtSender = new System.Windows.Forms.TextBox();
            this.button6 = new System.Windows.Forms.Button();
            this.SuspendLayout();
            // 
            // txtto
            // 
            this.txtto.Anchor = System.Windows.Forms.AnchorStyles.Top;
            this.txtto.Location = new System.Drawing.Point(159, 120);
            this.txtto.Name = "txtto";
            this.txtto.Size = new System.Drawing.Size(577, 29);
            this.txtto.TabIndex = 3;
            this.txtto.Text = "lehieu04044@gmail.com";
            // 
            // label1
            // 
            this.label1.Anchor = System.Windows.Forms.AnchorStyles.Top;
            this.label1.Location = new System.Drawing.Point(33, 123);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(107, 24);
            this.label1.TabIndex = 2;
            this.label1.Text = "Đến";
            // 
            // txtbody
            // 
            this.txtbody.Anchor = System.Windows.Forms.AnchorStyles.Top;
            this.txtbody.BackColor = System.Drawing.Color.White;
            this.txtbody.Location = new System.Drawing.Point(159, 297);
            this.txtbody.Name = "txtbody";
            this.txtbody.ReadOnly = true;
            this.txtbody.Size = new System.Drawing.Size(577, 206);
            this.txtbody.TabIndex = 5;
            this.txtbody.Text = resources.GetString("txtbody.Text");
            this.txtbody.Visible = false;
            // 
            // label2
            // 
            this.label2.Anchor = System.Windows.Forms.AnchorStyles.Top;
            this.label2.Location = new System.Drawing.Point(33, 197);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(107, 24);
            this.label2.TabIndex = 6;
            this.label2.Text = "Nội dung";
            this.label2.Visible = false;
            // 
            // label3
            // 
            this.label3.Anchor = System.Windows.Forms.AnchorStyles.Top;
            this.label3.Location = new System.Drawing.Point(33, 160);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(107, 24);
            this.label3.TabIndex = 4;
            this.label3.Text = "Tiêu đề";
            // 
            // txtsubject
            // 
            this.txtsubject.Anchor = System.Windows.Forms.AnchorStyles.Top;
            this.txtsubject.Location = new System.Drawing.Point(159, 157);
            this.txtsubject.Name = "txtsubject";
            this.txtsubject.Size = new System.Drawing.Size(577, 29);
            this.txtsubject.TabIndex = 4;
            this.txtsubject.Tag = "";
            // 
            // txtfrom
            // 
            this.txtfrom.Anchor = System.Windows.Forms.AnchorStyles.Top;
            this.txtfrom.Location = new System.Drawing.Point(159, 46);
            this.txtfrom.Name = "txtfrom";
            this.txtfrom.ReadOnly = true;
            this.txtfrom.Size = new System.Drawing.Size(577, 29);
            this.txtfrom.TabIndex = 0;
            this.txtfrom.Text = "pmlpvpos@gmail.com";
            // 
            // label4
            // 
            this.label4.Anchor = System.Windows.Forms.AnchorStyles.Top;
            this.label4.Location = new System.Drawing.Point(33, 47);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(107, 24);
            this.label4.TabIndex = 0;
            this.label4.Text = "Từ";
            // 
            // txtPass
            // 
            this.txtPass.Anchor = System.Windows.Forms.AnchorStyles.Top;
            this.txtPass.Location = new System.Drawing.Point(159, 83);
            this.txtPass.Name = "txtPass";
            this.txtPass.PasswordChar = '*';
            this.txtPass.ReadOnly = true;
            this.txtPass.Size = new System.Drawing.Size(577, 29);
            this.txtPass.TabIndex = 1;
            this.txtPass.Text = "lyphuvinh";
            // 
            // label5
            // 
            this.label5.Anchor = System.Windows.Forms.AnchorStyles.Top;
            this.label5.Location = new System.Drawing.Point(33, 85);
            this.label5.Name = "label5";
            this.label5.Size = new System.Drawing.Size(107, 24);
            this.label5.TabIndex = 10;
            this.label5.Text = "Mật khẩu";
            // 
            // timer1
            // 
            this.timer1.Enabled = true;
            this.timer1.Interval = 1000;
            this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
            // 
            // button5
            // 
            this.button5.Anchor = System.Windows.Forms.AnchorStyles.Top;
            this.button5.Font = new System.Drawing.Font("Times New Roman", 14F, System.Drawing.FontStyle.Bold);
            this.button5.Location = new System.Drawing.Point(484, 197);
            this.button5.Name = "button5";
            this.button5.Size = new System.Drawing.Size(118, 41);
            this.button5.TabIndex = 10;
            this.button5.Text = "Gửi";
            this.button5.Click += new System.EventHandler(this.button5_Click);
            // 
            // label6
            // 
            this.label6.Anchor = System.Windows.Forms.AnchorStyles.Top;
            this.label6.Location = new System.Drawing.Point(33, 297);
            this.label6.Name = "label6";
            this.label6.Size = new System.Drawing.Size(107, 24);
            this.label6.TabIndex = 12;
            this.label6.Text = "AttachFile";
            this.label6.Visible = false;
            // 
            // txtAttachFile
            // 
            this.txtAttachFile.Anchor = System.Windows.Forms.AnchorStyles.Top;
            this.txtAttachFile.Location = new System.Drawing.Point(159, 297);
            this.txtAttachFile.Name = "txtAttachFile";
            this.txtAttachFile.Size = new System.Drawing.Size(577, 29);
            this.txtAttachFile.TabIndex = 2;
            this.txtAttachFile.Text = "D:\\temp\\temp.rar";
            this.txtAttachFile.Visible = false;
            // 
            // label7
            // 
            this.label7.Anchor = System.Windows.Forms.AnchorStyles.Top;
            this.label7.Location = new System.Drawing.Point(33, 12);
            this.label7.Name = "label7";
            this.label7.Size = new System.Drawing.Size(107, 24);
            this.label7.TabIndex = 13;
            this.label7.Text = "Người gửi";
            // 
            // txtSender
            // 
            this.txtSender.Anchor = System.Windows.Forms.AnchorStyles.Top;
            this.txtSender.Location = new System.Drawing.Point(159, 9);
            this.txtSender.Name = "txtSender";
            this.txtSender.Size = new System.Drawing.Size(577, 29);
            this.txtSender.TabIndex = 14;
            this.txtSender.Text = "LPV_POS";
            // 
            // button6
            // 
            this.button6.Anchor = System.Windows.Forms.AnchorStyles.Top;
            this.button6.Font = new System.Drawing.Font("Times New Roman", 14F, System.Drawing.FontStyle.Bold);
            this.button6.ForeColor = System.Drawing.Color.Red;
            this.button6.Location = new System.Drawing.Point(619, 197);
            this.button6.Name = "button6";
            this.button6.Size = new System.Drawing.Size(118, 41);
            this.button6.TabIndex = 15;
            this.button6.Text = "Thoát";
            this.button6.Click += new System.EventHandler(this.button6_Click);
            // 
            // frmSendMail
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(9, 22);
            this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(224)))), ((int)(((byte)(224)))));
            this.ClientSize = new System.Drawing.Size(749, 251);
            this.Controls.Add(this.button6);
            this.Controls.Add(this.txtSender);
            this.Controls.Add(this.label7);
            this.Controls.Add(this.txtAttachFile);
            this.Controls.Add(this.label6);
            this.Controls.Add(this.button5);
            this.Controls.Add(this.label5);
            this.Controls.Add(this.txtPass);
            this.Controls.Add(this.txtbody);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.txtto);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label3);
            this.Controls.Add(this.txtsubject);
            this.Controls.Add(this.txtfrom);
            this.Controls.Add(this.label4);
            this.Font = new System.Drawing.Font("Times New Roman", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.Name = "frmSendMail";
            this.ShowIcon = false;
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = ".";
            this.Load += new System.EventHandler(this.Form1_Load);
            this.ResumeLayout(false);
            this.PerformLayout();

		}
		#endregion

        ///// <summary> 
        ///// The main entry point for the application. 
        ///// </summary> 
        //[STAThread] 
        //static void Main() 
        //{ 
        //    Application.Run(new frmSendMail());
        //}

        #region "   Send_Email"
        public void Send_Email(string sSender, string sFrom, string sPass, string sTo, string sSubject, string sbody, string sAttachFile, System.Windows.Forms.Cursor _Cursor)
        {
            //sAttachFile : Thư mục chứa tập tin cần gửi
            MailMessage msg = new MailMessage();
            msg.From = new MailAddress(sFrom, sSender, System.Text.Encoding.UTF8);
            msg.To.Add(sTo);
            msg.Bcc.Add(sFrom);
            msg.Subject = sSubject;
            msg.Body = sbody;
            msg.Priority = MailPriority.High;
            if (sAttachFile.Trim() != "")
            {
                //Kiem tra thu muc cần lấy có ko?
                if (Directory.Exists(sAttachFile))
                { 
                    //Lấy danh sách tập tin trong thư mục
                    string[] ListFile = Directory.GetFiles(sAttachFile);
                    if (ListFile != null)
                    {
                        for (int i = 0; i < ListFile.Length; i++)
                        {
                            Attachment att = new Attachment(ListFile[i]);
                            msg.Attachments.Add(att);
                        }
                    }
                    else
                    {
                        MessageBox.Show("File đính kèm không tồn tại.");
                    }
                }
                //if (new System.IO.FileInfo(sAttachFile).Exists)
                //{
                //   // Attachment att = new Attachment(sAttachFile);
                //    //System.Web.Mail.MailAttachment att = new System.Web.Mail.MailAttachment(sAttachFile);
                //   // msg.Attachments.Add(att);
                //}
                //else
                //    MessageBox.Show("File đính kèm không tồn tại.");
            }
            msg.SubjectEncoding = Encoding.UTF8;
            msg.BodyEncoding = Encoding.UTF8;
            msg.IsBodyHtml = true;
            msg.Priority = MailPriority.Normal;
            //
            SmtpClient client = new SmtpClient("smtp.gmail.com", 25);//bắt buộc phải là cổng 25 
            #region "   SMTP Gmail"
            client.UseDefaultCredentials = false;
            client.Credentials = new NetworkCredential(sFrom, sPass);    // thay bằng username và password của bạn  
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.EnableSsl = true;

            #endregion

            #region "   SMTP Ymail"
            //client.Credentials = new NetworkCredential(sFrom, sPass);    // thay bằng username và password của bạn  
            //client.Host = "smtp.mail.yahoo.com";
            //client.Port = 645;
            #endregion

            client.EnableSsl = true;        //server của gmail yêu cầu kết nối SSL (Secure Socket Layer) để bảo vệ thông tin đăng nhập  
            client.SendCompleted += new SendCompletedEventHandler(client_SendCompleted);
            object userState = msg;
            client.SendAsync(msg, userState);
            //client.Send(msg);
        }
        #endregion
        
        #region 1.InitControl

        private void InitControl()
        {
            txtAttachFile.Text = Application.StartupPath + @"\AttachFile";
            txtto.Leave += new EventHandler(txtto_Leave);
            //Load Email
            DataSet ds = new thuvien().sql_SelectDataset("DM_COMPANY");
            if (ds != null)
            {
                txtto.Text = ds.Tables[0].Rows[0]["EMAIL"] + "";
            }
        }

        void txtto_Leave(object sender, EventArgs e)
        {
            if (!new cpublic().IsValidEmailAddress(txtto.Text))
            {
                MessageBox_LPV.Show("Email không hợp lệ.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtto.Focus();
                return;
            }
        }

        #endregion

        #region 2.Xử lý Button

        private void button5_Click(object sender, EventArgs e)
        {
            //Kiem tra mang internet
            if (!IsConnected())
            {
                MessageBox_LPV.Show("Mạng Internet không kết nối.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            this.Cursor = Cursors.WaitCursor;
            this.Send_Email(txtSender.Text, txtfrom.Text, txtPass.Text, txtto.Text, txtsubject.Text, txtbody.Text, txtAttachFile.Text, this.Cursor);

        }

        private bool IsConnected()
        {
            System.Uri Url = new System.Uri("http://www.google.com");

            System.Net.WebRequest WebReq;
            System.Net.WebResponse Resp;
            WebReq = System.Net.WebRequest.Create(Url);

            try
            {
                Resp = WebReq.GetResponse();
                Resp.Close();
                WebReq = null;
                return true;
            }

            catch
            {
                WebReq = null;
                return false;
            }
        }

        private void button6_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        #endregion

        #region 3.Xử lý sự kiện

        private void Form1_Load(object sender, EventArgs e)
        {
            txtsubject.Text = txtsubject.Text + "Báo cáo bán hàng - " + DateTime.Now.ToString();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            this.Text = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss");
        }

        void client_SendCompleted(object sender, AsyncCompletedEventArgs e)
        {
            this.Cursor = Cursors.Default;
            bool flag = false;
            if (e != null)
            {
                String token = "Thông báo";// (string)e.UserState;

                if (e.Cancelled)
                {
                    MessageBox.Show("Gửi thất bại", token);
                }
                if (e.Error != null)
                {
                    MessageBox.Show(e.Error + "", token);
                }
                else
                {
                    flag = true;
                    MessageBox.Show("Gửi thành công", token);
                }
                ///////////////
                MailMessage msg = (MailMessage)e.UserState;
                if (msg != null)
                    msg.Dispose();
                if (flag == true)
                {
                    this.Close();
                    string folder = Application.StartupPath + @"\AttachFile";
                    //Kiểm tra folder có tồn tại không?
                    if (Directory.Exists(folder))
                    { 
                        //duyệt qua các file và xóa file
                        string []strFile=Directory.GetFiles(folder);
                        foreach (string str in strFile)
                        {
                            //kiem tra truoc khi xoa
                            if(File.Exists(str))
                                File.Delete(str);
                        }
                    }
                }
            }
        }

        #endregion

    }
}
